# coding: utf-8 
# 中文排序样例
# Sorting Chinese Character
# henrysting@163.com
# 2009-12-25
from __future__ import division
import sys
reload(sys) 
sys.setdefaultencoding('utf8')
import datetime
import re
import redis
import settings
import pylibmc

class fakemc():
    def set(key,value,mem,*args):
        pass
    def get(key,value):
        return ""

def setmc():
    if settings.cache_on == 0:
        mc = fakemc()
        return mc
    else:
        return pylibmc.Client(["%s" % settings.cache_servers], binary=True)

def setredis(_key):
    try:
        r = redis.Redis("%s" % settings.redis_server,settings.redis_port,0)
        keys = r.hgetall('weburlcachekey')
        keystr = keys.get('keys')
        keylists = eval(keystr)
        keylists = list(keylists)
        keylists.append(_key)
        keylists = set(keylists)
        r.hset('weburlcachekey','keys',keylists)
    except:
        pass
    
    
def huoyuezhou(riqi):
    _stimelist = riqi.split("-")
    _stime = _stimelist[0]
    yy =  _stime[0:4]
    mm =  _stime[4:6]
    dd =  _stime[6:]
    testdate = datetime.datetime(int(yy),int(mm),int(dd))
    zhou = (testdate.day+7-1)/7
    #zhou = week(int(yy),int(mm),int(dd))
    #if str(mm) == '10':
    #    zhou = zhou + 1
    #if zhou == 0:
    #    zhou = 1
    return u"%s/%s-第%s周" % (yy,mm,int(zhou))

def huoyuez(riqi):
    _stimelist = riqi.split("-")
    _stime = _stimelist[0]
    _stime1 = _stimelist[1]
    
    
    yy =  _stime[0:4]
    mm =  _stime[4:6]
    dd =  _stime[6:]
    
    yy1 =  _stime1[0:4]
    mm1 =  _stime1[4:6]
    dd1 =  _stime1[6:]
    
    if(int(dd1) - int(dd) >= 15):
        return "%s/%s" % (yy,mm)
    else:
        testdate = datetime.datetime(int(yy),int(mm),int(dd))
        zhou = (testdate.day+7-1)/7
        #zhou = week(int(yy),int(mm),int(dd))
        #if str(mm) == '10':
        #    zhou = zhou + 1
        #if zhou == 0:
        #    zhou = 1
        return u"%s/%s-第%s周" % (yy,mm,int(zhou))

def huoyueyue(riqi):
    _stimelist = riqi.split("-")
    _stime = _stimelist[0]
    yy =  _stime[0:4]
    mm =  _stime[4:6]
    dd =  _stime[6:]
    zhou = week(int(yy),int(mm),int(dd))
    return "%s/%s" % (yy,mm)


def week(year, month, day):
    first_week_month = datetime.datetime(year, month, 1).isocalendar()[1]
    if month == 1 and first_week_month > 10:
        first_week_month = 0
    user_date = datetime.datetime(year, month, day).isocalendar()[1]
    if month == 1 and user_date > 10:
        user_date = 0
    return user_date - first_week_month

def fordate(riqi,_type):
    yy = riqi[0:4]
    mm = riqi[4:6]
    dd = riqi[6:]
    
    if _type == 1:
        return "%s.%s.%s" % (yy,mm,dd)
    elif _type == 2:
        return "%s/%s" % (yy,mm)
    elif _type == 3:
        return "%s/%s/%s" % (yy,mm,dd)

#将统计项缩写名字列表转换成全称
def valueFullNameArr(checkedItems):
    fullName = []
    for n in checkedItems:
        if(n == "UV"):
            fullName.append("使用设备数(UV)")
        elif(n == "VV"):
            fullName.append("播放总量(VV)")
        elif(n == "NU"):
            fullName.append("新增设备数(NU)")
        elif(n == "VVUV"):
            fullName.append("VV/UV")
        elif(n == "Dur"):
            fullName.append("总时长(min)")
        elif(n == "DurVV"):
            fullName.append("总时长/VV<br>(min)")
        elif(n == "DurUV"):
            fullName.append("总时长/UV<br>(min)")
        elif(n == "Comp"):
            fullName.append("播放完成量")
        elif(n == "CompVV"):
            fullName.append("播放完成率")
        elif(n == "BefDurTime"):
            fullName.append("播放前<br>平均加载时长<br>(s)")
        elif(n == "PlayDurTime"):
            fullName.append("播放中<br>平均加载时长<br>(s)")
        elif(n == "PlayTimeVV"):
            fullName.append("单次播放<br>平均加载次数")
        elif(n == "PlayDurVV"):
            fullName.append("播放中<br>单次加载平均时长<br>(s)")
        elif(n == "HDSDDurTime"):
            fullName.append("高清->标清<br>平均加载时长<br>(s)")
        elif(n == "SDHDDurTime"):
            fullName.append("标清->高清<br>平均加载时长<br>(s)")
        elif(n == "RelateAPIAveRespTime"):
            fullName.append("相关接口<br>平均响应时长<br>(s)")
        elif(n == "VdDetailAPIAveRespTime"):
            fullName.append("详情接口<br>平均响应时长<br>(s)")
        elif(n == "VdUrlAPIAveRespTime"):
            fullName.append("视频地址接口<br>平均响应时长<br>(s)")	
        elif(n == "NR"):
            fullName.append("注册用户数(NR)")	
        elif(n == "SU"):
            fullName.append("成功上传量(SU)")
        elif(n == "downloadnum"):
            fullName.append("下载量")
        elif(n == "updatenum"):
            fullName.append("更新量")
	
    return fullName




def checkValueMode(value):
    if (value == 'VVUV' or value == 'DurVV' or value == 'DurUV' or value == 'CompVV' or value == 'BefDurTime' or value == 'PlayDurTime' or value == 'PlayTimeVV' or value == 'PlayDurVV' or value == 'HDSDDurTime' or value == 'SDHDDurTime' or value == 'RelateAPIAveRespTime' or value == 'VdDetailAPIAveRespTime' or value == 'VdUrlAPIAveRespTime' or value == 'transcodetime' or value == 'HD2DurTime'):
        return True
    else:
        return False



def genTableResultInc3(_last,_now,value,xy,bdurtimeall):
    
    
    try:
        cha = _now - _last
    except:
        cha = 0
                    
    if cha > 0:
        jiantou = "<span class='inc_tag' style='margin-left: 5px;' title='0%'><b> ↑ </b></span>"
    elif cha < 0:
        jiantou = "<span class='des_tag' style='margin-left: 5px;' title='0%'><b> ↓ </b></span>"
    else:
        jiantou = "<span style='margin-left: 5px;' title='0%'><b> - </b></span>"
    if xy == 0:
        jiantou = "<span style='margin-left: 5px;' title='0%'><b> - </b></span>"
    
    
    
    if value == "CompVV":
        _str = "<td>"
        nl = str(_now).split(".")
        #print nl
        if len(str(nl[1])) < 4:
            shu = "%s0%s" % (_now * 100,"%")
        else:
            shu = "%s%s" % (_now * 100,"%")
            
        _str += "%s%s</td>" % (shu,jiantou)
    
    elif value == "BefDurTime123":
        _str = "<td style='padding:0px;'>"
        
        #print _now
        
        pingjun = _now
        
        bdurtime = bdurtimeall[xy]['bdurtime']
        
        
        
        
        nl = str(bdurtime['b3']).split(".")
        #print nl
        if len(str(nl[1])) < 4:
            shu = "%s0%s" % (bdurtime['b3'] * 100,"%")
        else:
            shu = "%s%s" % (bdurtime['b3'] * 100,"%")
        b3 = shu
        
        #print b3
        
        
        
        nl = str(bdurtime['b5']).split(".")
        #print nl
        if len(str(nl[1])) < 4:
            shu = "%s0%s" % (bdurtime['b5'] * 100,"%")
        else:
            shu = "%s%s" % (bdurtime['b5'] * 100,"%")
        b5 = shu
        
        
        nl = str(bdurtime['b8']).split(".")
        #print nl
        if len(str(nl[1])) < 4:
            shu = "%s0%s" % (bdurtime['b8'] * 100,"%")
        else:
            shu = "%s%s" % (bdurtime['b8'] * 100,"%")
        b8 = shu
        
       
        nl = str(bdurtime['b300']).split(".")
        #print nl
        if len(str(nl[1])) < 4:
            shu = "%s0%s" % (bdurtime['b300'] * 100,"%")
        else:
            shu = "%s%s" % (bdurtime['b300'] * 100,"%")
        b300 = shu
        
        nl = str(bdurtime['b301']).split(".")
        #print nl
        if len(str(nl[1])) < 4:
            shu = "%s0%s" % (bdurtime['b301'] * 100,"%")
        else:
            shu = "%s%s" % (bdurtime['b301'] * 100,"%")
        b301 = shu
        
        _str += "<div class='verdivri'>%s</div><div class='verdivri'>%s</div><div class='verdivri'>%s</div><div class='verdivri'>%s</div><div class='verdivri'>%s</div><div class='verdivri'>%s</div></td>" % (pingjun,b3,b5,b8,b300,b301)
        
    elif value == "PlayDurTime123":
        _str = "<td style='padding:0px;'>"
        
        #print _now
        
        pingjun = _now
        
        bdurtime = bdurtimeall[xy]['pdurtime']
        
        
        
        
        nl = str(bdurtime['p3']).split(".")
        #print nl
        if len(str(nl[1])) < 4:
            shu = "%s0%s" % (bdurtime['p3'] * 100,"%")
        else:
            shu = "%s%s" % (bdurtime['p3'] * 100,"%")
        p3 = shu
        
        #print b3
        
        
        
        nl = str(bdurtime['p5']).split(".")
        #print nl
        if len(str(nl[1])) < 4:
            shu = "%s0%s" % (bdurtime['p5'] * 100,"%")
        else:
            shu = "%s%s" % (bdurtime['p5'] * 100,"%")
        p5 = shu
        
        
        nl = str(bdurtime['p8']).split(".")
        #print nl
        if len(str(nl[1])) < 4:
            shu = "%s0%s" % (bdurtime['p8'] * 100,"%")
        else:
            shu = "%s%s" % (bdurtime['p8'] * 100,"%")
        p8 = shu
        
       
        nl = str(bdurtime['p300']).split(".")
        #print nl
        if len(str(nl[1])) < 4:
            shu = "%s0%s" % (bdurtime['p300'] * 100,"%")
        else:
            shu = "%s%s" % (bdurtime['p300'] * 100,"%")
        p300 = shu
        
        nl = str(bdurtime['p301']).split(".")
        #print nl
        if len(str(nl[1])) < 4:
            shu = "%s0%s" % (bdurtime['p301'] * 100,"%")
        else:
            shu = "%s%s" % (bdurtime['p301'] * 100,"%")
        p301 = shu
        
        _str += "<div class='verdivri'>%s</div><div class='verdivri'>%s</div><div class='verdivri'>%s</div><div class='verdivri'>%s</div><div class='verdivri'>%s</div><div class='verdivri'>%s</div></td>" % (pingjun,p3,p5,p8,p300,p301)
        
        
        
    else:
        _str = "<td>"
        if checkValueMode(value):
            #print _now
            nl = str(_now).split(".")
            if len(str(nl[1])) < 2:
                shu = "%s0%s" % (_now,"")
            else:
                shu = "%s%s" % (_now,"")
        else:
            shu = "%s%s" % (num2money(_now),"")
    
        _str += "%s%s</td>" % (shu,jiantou)
    
    return _str
    
def genTableResultInc5(_last,_now,value,xy,bdurtimeall,vvv):
    
    
    try:
        cha = _now - _last
    except:
        cha = 0
                    
    if cha > 0:
        jiantou = "<span class='inc_tag' style='margin-left: 5px;' title='0%'><b>  </b></span>"
    elif cha < 0:
        jiantou = "<span class='des_tag' style='margin-left: 5px;' title='0%'><b>  </b></span>"
    else:
        jiantou = "<span style='margin-left: 5px;' title='0%'><b>  </b></span>"
    if xy == 0:
        jiantou = "<span style='margin-left: 5px;' title='0%'><b>  </b></span>"
    
    
    if value == "CompVV":
        _str = "<div class='verdiv'>"
        nl = str(_now).split(".")
        #print nl
        if len(str(nl[1])) < 4:
            shu = "%s0%s" % (_now * 100,"%")
        else:
            shu = "%s%s" % (_now * 100,"%")
        
        _str += "%s%s<span style='display:none'>  |  </span></div>" % (shu,jiantou)
    
    
    elif value == "BefDurTime123":
        
        _str = "<div style='float:left;display:inline;border-right:1px solid #D8D7D7;'>"
        
        #print _now
        
        pingjun = _now
        
        bdurtime = bdurtimeall[xy]['teams'][vvv].get('bdurtime')
        
        #print bdurtimeall
        
        
        nl = str(bdurtime['b3']).split(".")
        #print nl
        if len(str(nl[1])) < 4:
            shu = "%s0%s" % (bdurtime['b3'] * 100,"%")
        else:
            shu = "%s%s" % (bdurtime['b3'] * 100,"%")
        b3 = shu
        
        
        nl = str(bdurtime['b5']).split(".")
        #print nl
        if len(str(nl[1])) < 4:
            shu = "%s0%s" % (bdurtime['b5'] * 100,"%")
        else:
            shu = "%s%s" % (bdurtime['b5'] * 100,"%")
        b5 = shu
        
        
        nl = str(bdurtime['b8']).split(".")
        #print nl
        if len(str(nl[1])) < 4:
            shu = "%s0%s" % (bdurtime['b8'] * 100,"%")
        else:
            shu = "%s%s" % (bdurtime['b8'] * 100,"%")
        b8 = shu
        
        nl = str(bdurtime['b300']).split(".")
        #print nl
        if len(str(nl[1])) < 4:
            shu = "%s0%s" % (bdurtime['b300'] * 100,"%")
        else:
            shu = "%s%s" % (bdurtime['b300'] * 100,"%")
        b300 = shu
        
        nl = str(bdurtime['b301']).split(".")
        #print nl
        if len(str(nl[1])) < 4:
            shu = "%s0%s" % (bdurtime['b301'] * 100,"%")
        else:
            shu = "%s%s" % (bdurtime['b301'] * 100,"%")
        b301 = shu
        
        _str += "<div class='verdivri'>%s</div><div class='verdivri'>%s</div><div class='verdivri'>%s</div><div class='verdivri'>%s</div><div class='verdivri'>%s</div><div class='verdivri'>%s</div></div>" % (pingjun,b3,b5,b8,b300,b301)
    
    
    elif value == "PlayDurTime123":
        
        _str = "<div style='float:left;display:inline;border-right:1px solid #D8D7D7;'>"
        
        #print _now
        
        pingjun = _now
        
        bdurtime = bdurtimeall[xy]['teams'][vvv].get('pdurtime')
        
        #print bdurtimeall
        
        
        nl = str(bdurtime['p3']).split(".")
        #print nl
        if len(str(nl[1])) < 4:
            shu = "%s0%s" % (bdurtime['p3'] * 100,"%")
        else:
            shu = "%s%s" % (bdurtime['p3'] * 100,"%")
        p3 = shu
        
        
        nl = str(bdurtime['p5']).split(".")
        #print nl
        if len(str(nl[1])) < 4:
            shu = "%s0%s" % (bdurtime['p5'] * 100,"%")
        else:
            shu = "%s%s" % (bdurtime['p5'] * 100,"%")
        p5 = shu
        
        
        nl = str(bdurtime['p8']).split(".")
        #print nl
        if len(str(nl[1])) < 4:
            shu = "%s0%s" % (bdurtime['p8'] * 100,"%")
        else:
            shu = "%s%s" % (bdurtime['p8'] * 100,"%")
        p8 = shu
        
        nl = str(bdurtime['p300']).split(".")
        #print nl
        if len(str(nl[1])) < 4:
            shu = "%s0%s" % (bdurtime['p300'] * 100,"%")
        else:
            shu = "%s%s" % (bdurtime['p300'] * 100,"%")
        p300 = shu
        
        nl = str(bdurtime['p301']).split(".")
        #print nl
        if len(str(nl[1])) < 4:
            shu = "%s0%s" % (bdurtime['p301'] * 100,"%")
        else:
            shu = "%s%s" % (bdurtime['p301'] * 100,"%")
        p301 = shu
        
        _str += "<div class='verdivri'>%s</div><div class='verdivri'>%s</div><div class='verdivri'>%s</div><div class='verdivri'>%s</div><div class='verdivri'>%s</div><div class='verdivri'>%s</div></div>" % (pingjun,p3,p5,p8,p300,p301)
    
    else:
        _str = "<div class='verdiv'>"
        if checkValueMode(value):
            nl = str(_now).split(".")
            if len(str(nl[1])) < 2:
                shu = "%s0%s" % (_now,"")
            else:
                shu = "%s%s" % (_now,"")
        else:
            shu = "%s%s" % (num2money(_now),"")
    
        _str += "%s%s<span style='display:none'>  |  </span></div>" % (shu,jiantou)
    
    return _str
    
def genTableResultInc4(_last,_now,value,xy):
    _str = "<td>"
    
    cha = _now - _last
                    
    if cha > 0:
        jiantou = "<span class='inc_tag' style='margin-left: 5px;' title='0%'><b> ↑ </b></span>"
    elif cha < 0:
        jiantou = "<span class='des_tag' style='margin-left: 5px;' title='0%'><b> ↓ </b></span>"
    else:
        jiantou = "<span style='margin-left: 5px;' title='0%'><b> - </b></span>"
    if xy == 0:
        jiantou = "<span style='margin-left: 5px;' title='0%'><b> - </b></span>"
    
    
    if value == "huoyuelv":
        nl = str(_now).split(".")
        if len(str(nl[1])) < 4:
            shu = "%s0%s" % (_now * 100,"%")
        else:
            shu = "%s%s" % (_now * 100,"%")
    else:
        if checkValueMode(value):
            shu = "%s%s" % (_now,"")
        else:
            shu = "%s%s" % (num2money(_now),"")
    
    _str += "%s%s</td>" % (shu,jiantou)
    
    return _str



def num2money(num, decimals = 0, err = ''):
    u''' 将数字格式化为金额样式，参数为数值，返回字符串

    num         要转换的数值
    decimals    保留小数位数
    err         出现错误时的返回值
    '''
    try:
        s = '' if num >= 0 else '-'
        y = r'%.' + str(decimals) + 'f'
        x = y % abs(num)
        decimal2 = decimals + 1 if decimals else decimals
        for i in range(len(x) - decimal2 - 3, 0, -3):
            x = '%s,%s' % (x[:i], x[i:])
        return '%s%s' % (s, x)
    except:
        return err



def multi_get_letter(str_input):
    
    if isinstance(str_input, unicode):
        unicode_str = str_input
    else:
        try:
            unicode_str = str_input.decode('utf8')
        except:
            try:
                unicode_str = str_input.decode('gbk')
            except:
                print 'unknown coding'
                return
    
    return_list = []
    for one_unicode in unicode_str:
        #print single_get_first(one_unicode)
        return_list.append(single_get_first(one_unicode))
    return "".join(return_list)    
    
def single_get_first(unicode1):
    str1 = unicode1.encode('gbk')
    try:        
        ord(str1)
        return str1
    except:
        asc = ord(str1[0]) * 256 + ord(str1[1]) - 65536
        if asc >= -20319 and asc <= -20284:
            return 'a'
        if asc >= -20283 and asc <= -19776:
            return 'b'
        if asc >= -19775 and asc <= -19219:
            return 'c'
        if asc >= -19218 and asc <= -18711:
            return 'd'
        if asc >= -18710 and asc <= -18527:
            return 'e'
        if asc >= -18526 and asc <= -18240:
            return 'f'
        if asc >= -18239 and asc <= -17923:
            return 'g'
        if asc >= -17922 and asc <= -17418:
            return 'h'
        if asc >= -17417 and asc <= -16475:
            return 'j'
        if asc >= -16474 and asc <= -16213:
            return 'k'
        if asc >= -16212 and asc <= -15641:
            return 'l'
        if asc >= -15640 and asc <= -15166:
            return 'm'
        if asc >= -15165 and asc <= -14923:
            return 'n'
        if asc >= -14922 and asc <= -14915:
            return 'o'
        if asc >= -14914 and asc <= -14631:
            return 'p'
        if asc >= -14630 and asc <= -14150:
            return 'q'
        if asc >= -14149 and asc <= -14091:
            return 'r'
        if asc >= -14090 and asc <= -13119:
            return 's'
        if asc >= -13118 and asc <= -12839:
            return 't'
        if asc >= -12838 and asc <= -12557:
            return 'w'
        if asc >= -12556 and asc <= -11848:
            return 'x'
        if asc >= -11847 and asc <= -11056:
            return 'y'
        if asc >= -11055 and asc <= -10247:
            return 'z'
        return ''


  
